<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<%@ taglib prefix="memberForm" uri="http://www.tongxingzhe.cn/memberForm" %>
<%@ page import="com.party.core.model.system.TargetType" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${activity == null ? '发布' : '编辑'}活动</title>
    <%@include file="../include/commonFile.jsp" %>
    <script src="//api.map.baidu.com/api?v=2.0&ak=2izIwlMmDVH737ms8m4Y8uHsoxtEIR65"></script>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <style type="text/css">
        .add-form-content .form-inner {
            padding: 10px;
        }

        .border {
            border: 1px solid #eee;
            padding-left: 0px;
            padding-right: 0px;
            border-radius: 4px;
        }

        fieldset legend {
            font-size: 18px;
            margin-left: 30px;
        }
    </style>
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/activity/activity/save.do">
                    <fieldset class="border mb10">
                        <legend>活动基本信息</legend>
                        <div class="form-inner">
                            <div class="layui-form-item">
                                <label class="layui-form-label">所属合作商<span class="f-verify-red">*</span></label>
                                <div class="layui-input-inline">
                                    <input type="hidden" name="member" lay-verify="orgId" value="${activity.member}"/>
                                    <input type="text" id="member_name" value="${memberForm:getRealNameById(activity.member)}" class="layui-input" readonly/>
                                </div>
                                <c:if test="${empty activity.id}">
                                    <a class="layui-btn layui-btn-danger" type="button" onclick="openSelMemberDialog(this,'选择所属合作商','${ctx}/system/member/selectPartner.do','950px','570px')">
                                        选择
                                    </a>
                                </c:if>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">活动标题<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="title" lay-verify="title" autocomplete="off" maxlength="50" placeholder="活动标题" class="layui-input" value="${activity.title}">
                                    <input type="hidden" name="id" value="${activity.id}"/>
                                    <input type="hidden" name="isCrowdfunded" value="${activity.isCrowdfunded == null ? 0 : activity.isCrowdfunded}"/>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">海报<span class="f-verify-red">*</span></label>
                                <div class="cover-content">
                                    <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${activity.pic}"/>
                                    <c:if test="${activity == null || empty activity.pic}">
                                        <span id="cover-img" class="cover-img" style="background-image:url(${ctx}/image/posterImg.png)"></span>
                                    </c:if>
                                    <c:if test="${activity != null && not empty activity.pic}">
                                        <span id="cover-img" class="cover-img" style="background-image:url('${activity.pic}')"></span>
                                    </c:if>
                                    <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加海报</a>
                                    <div class="form-word-aux">建议尺寸：800x450</div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">报名截止时间<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input class="layui-input" name="endDate" lay-verify="endDate" placeholder="报名截止时间"
                                           id="endTime" style="width: 190px; float: left; margin-right: 10px;" readonly
                                           value='<fmt:formatDate value="${activity.endTime}" pattern="yyyy-MM-dd HH:mm" />'
                                    />
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">活动开始时间<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input class="layui-input" name="startDate" lay-verify="startDate" placeholder="活动开始时间"
                                           id="startTime" style="width: 190px; float: left; margin-right: 10px;" readonly
                                           value='<fmt:formatDate value="${activity.startTime}" pattern="yyyy-MM-dd HH:mm" />'
                                    />
                                </div>
                            </div>
                            <%@include file="./cityAreaMapNew.jsp" %>
                            <div id="mapDiv" class="layui-form-item" style="display: none;">
                                <div class="layui-inline">
                                    <label class="layui-form-label"></label>
                                    <div class="layui-input-inline">
                                        <div id="allmap" style="height: 500px;"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">报名费用<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <%@include file="../include/counterfoil.jsp" %>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">微网站置顶效果<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="micWebStatus" value="1" title="是"
                                    ${activity == null || activity.micWebStatus == 1 ? 'checked="checked"' : ''}
                                    >
                                    <input type="radio" name="micWebStatus" value="0" title="否"
                                    ${activity != null && activity.micWebStatus == 0 ? 'checked="checked"' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">持邀请码参与<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="inviteOnly" lay-filter="isInvite" id="invite_yes" value="1" title="是"
                                    ${activity != null && activity.inviteOnly == 1 ? 'checked="checked"' : ''}
                                    >
                                    <input type="radio" name="inviteOnly" lay-filter="isInvite" id="invite_no" value="0" title="否"
                                    ${activity == null || activity.inviteOnly == 0 ? 'checked="checked"' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item"
                                 id="inviteCodeDiv" ${empty activity.id || activity.inviteOnly == 0 ? 'style="display:none"' : ''}>
                                <div class="layui-inline">
                                    <label class="layui-form-label">邀请码<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="inviteCode" lay-verify="inviteCode" class="layui-input" value="${activity.inviteCode}"/>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">隐藏报名人员<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="joinHidden" value="1" title="是"
                                    ${activity == null || activity.joinHidden == 1 ? 'checked="checked"' : ''}
                                    >
                                    <input type="radio" name="joinHidden" value="0" title="否"
                                    ${activity != null && activity.joinHidden == 0 ? 'checked="checked"' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">显示在前端<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="showFront" value="1" title="是"
                                    ${activity == null || activity.showFront == 1 ? 'checked="checked"' : ''}
                                    >
                                    <input type="radio" name="showFront" value="0" title="否"
                                    ${activity != null && activity.showFront == 0 ? 'checked="checked"' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">在其他城市显示<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="radio" name="isAllowedOutside" value="1" title="是"
                                    ${activity != null && activity.isAllowedOutside == 1 ? 'checked="checked"' : ''}
                                    >
                                    <input type="radio" name="isAllowedOutside" value="0" title="否"
                                    ${activity == null || activity.isAllowedOutside == 0 ? 'checked="checked"' : ''}
                                    >
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">排序号</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="sort" lay-verify="sort" autocomplete="off" class="layui-input" value="${activity.sort}">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">活动描述</label>
                                <div class="layui-input-block">
                                    <input type="text" name="remarks" placeholder="活动描述" class="layui-input" maxlength="100" value="${activity.remarks}">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">活动详情<span class="f-verify-red">*</span></label>
                                <div class="layui-input-block">
                                    <script id="ueditor1" type="text/plain"></script>
                                    <div style="display: none" id="contentView">${activityDetail.content}</div>
                                    <input type="hidden" name="content" id="content" lay-verify="content" data-link-ue="ueditor1"/>
                                </div>
                            </div>
                        </div>
                    </fieldset>
                    <fieldset class="border mb10">
                        <legend>活动报名表单</legend>
                        <div class="form-inner">
                            <%@include file="../gatherForm/activityCreateForm.jsp"%>
                            <div class="cl"></div>
                        </div>
                    </fieldset>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                            <a href="${ctx}/activity/activity/activityList.do" class="layui-btn layui-btn-primary">取消</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <!--底部-->
        <%@include file="../include/footer.jsp" %>

        <div style="display: none" id="create_date_str">
            <fmt:formatDate value="${activity.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>
        </div>
        <c:if test="${not empty activity.member}">
            <c:set var="expirationTime" value="${memberForm:getExpirationTimeById(activity.member)}"/>
            <c:set var="isExpire" value="${memberForm:isExpire(activity.member, null)}"/>
        </c:if>
    </section>
</div>

<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>
<script>
    var ue = UE.getEditor('ueditor1'), form, laydate, formcache;
    var groupExpirationDate, endLaydate = {};

    txz.initHeader({
        nav: [{
            name: '活动管理',
            href: '${ctx}/activity/activity/activityList.do',
        }, {
            name: '${activity == null ? '发布' : '编辑'}活动',
            curr: true
        }],
        btns: [{
            type: 'back'
        }]
    });
    $(function () {
        layui.use(['form', 'laydate'], function () {
            form = layui.form, laydate = layui.laydate;
            var freeRadioValue = null;
            var inviteRadioValue = null;

            form.on('radio(isCrowdfunded)', function (data) {
                var value = data.value;
                if (value == "0") {
                    $('#noFree').attr('checked', false);
                    $('#free').attr('disabled', false);
                } else if (value == "1") {
                    $('#noFree').attr('checked', 'checked');
                    $('#free').attr('disabled', 'disabled');
                }
            });
            form.on('radio(isFree)', function (data) {
                freeRadioValue = data.value;
                if (freeRadioValue == "noFree") {
                    $("[name=price]").prop("disabled", false);
                } else {
                    $("[name=price]").val("");
                    $("[name=price]").prop("disabled", true);
                }
            });

            form.on('radio(isInvite)', function (data) {
                inviteRadioValue = data.value;
                if (inviteRadioValue == "1") {
                    $("#inviteCodeDiv").show();
                } else {
                    $("#inviteCodeDiv").hide();
                    $("#inviteCodeDiv input[type=text]").val("");
                }
            });

            //自定义验证规则
            form.verify({
                orgId: function (value) {
                    if (!value) {
                        return "请选择所属合作商"
                    }
                    if ('${isExpire}' == 'true') {
                        return "当前合作商已到期，不能发布数据"
                    }
                },
                title: function (value) {
                    if (value == "") {
                        return '请填写活动标题';
                    }
                },
                pic: function (value) {
                    if (value == "") {
                        return "请上传活动海报";
                    }
                },
                endDate: function (value) {
                    if (value == "") {
                        return "请设置报名截止时间";
                    }

                    if (util.getTimeMillis(value) < util.getTimeMillis()) {
                        return "截止时间不得早于当前时间";
                    }

                    if (groupExpirationDate) {
                        if (value >= groupExpirationDate) {
                            return "截止时间不能超过账户过期时间";
                        }
                    } else if ('${expirationTime}') {
                        var max = '${memberForm:dateFormat(expirationTime, 'yyyy-MM-dd HH:mm:ss')}';
                        if (value >= max) {
                            return "截止时间不能超过账户过期时间";
                        }
                    }
                },
                startDate: function (value) {
                    if (value == "") {
                        return "请设置活动开始时间";
                    }

                    if (util.getTimeMillis(value) < util.getTimeMillis()) {
                        return "活动开始时间不得早于当前时间"
                    }

/*                    var endDate = $("[name=endDate]").val();
                    if (value <= endDate) {
                        return "活动开始时间不能早于报名截止时间";
                    }*/
                },
                place: function (value) {
                    if (value == "") {
                        return "请设置活动场所";
                    }
                },
                area: function (value) {
                    if (value == "") {
                        return "请设置活动区域";
                    }
                },
// 			lng : function(value){
// 				if(value == ""){
// 					return "请填写经度"
// 				}
// 			},
// 			lat : function(value){
// 				if(value == ""){
// 					return "请填写纬度"
// 				}
// 			},
                city: function (value) {
                    if (value == "") {
                        return "请选择活动举办的城市";
                    }
                },
                limitNum: function (value) {
                    if (value == "") {
                        return "请设置活动人数上限";
                    } else if (!util.checkNumber(value)) {
                        return "请输入正确的数字";
                    } else if (parseInt(value) == 0) {
                        return "请输入大于0的数字";
                    }
                },
                price: function (value) {
                    var reg = /^(([0-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/;
                    if (freeRadioValue == null) {
                        var type = $("[name=isFree]:checked").val();
                        if (type == "noFree") {
                            if (value == "") {
                                return "请设置活动报名金额";
                            } else if (!reg.test(value)) {
                                return "请输入正确的金额";
                            }
                        }
                    } else {
                        if (freeRadioValue == "noFree") {
                            if (value == "") {
                                return "请设置活动报名金额";
                            } else if (!reg.test(value)) {
                                return "请输入正确的金额";
                            }
                        }
                    }
                },
                inviteCode: function (value) {
                    if (inviteRadioValue == null) {
                        var invite = $("[name=inviteOnly]:checked").val();
                        if (invite == "1") {
                            if (value == "") {
                                return "请填写邀请码";
                            }
                        }
                    } else {
                        if (inviteRadioValue == "1") {
                            if (value == "") {
                                return "请填写邀请码";
                            }
                        }
                    }
                },
                sort: function (value) {
                    if (!util.checkNumber(value)) {
                        return "请输入正确的数字";
                    }
                },
                content: function (value) {
                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (content == "") {
                        return "请填写活动详情";
                    }
                }
            });

            form.render('radio');
            form.render('checkbox');
            form.render('select');

            //监听提交
            form.on('submit', function (data) {
                if (checkCost() && checkField()) {
                    submitForm(data);
                }
            });

            function submitForm(data) {
                txz.submitObject(data.elem, function (callBack) {
                    resetIndex();
                    resetFormIndex();
                    var action = $("#myForm").attr("action");
                    var formData = getFormData();
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: true,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    location.href = "${ctx}/activity/activity/activityList.do";
                                })
                            } else {
                                util.layerMsgError("提交失败")
                            }
                        }
                    });
                });
            }

            var min;
            if (${empty activity.id}) {
                min = new Date().Format('yyyy-MM-dd HH:mm:ss');
            } else {
                min = $("#create_date_str").text();
            }

            var max = '${memberForm:dateFormat(expirationTime, 'yyyy-MM-dd HH:mm:ss')}';

            endLaydate = laydate.render({
                elem: '#endTime',
                min: min,
                max: max || '2099-06-16 23:59',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm' //日期格式
            });


            //日期
            var start = {
                elem: '#startTime',
                min: min,
                max: '2099-06-16 23:59',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm'
            };

            laydate.render(start);

            //初始化地图控件
            txz.Map.init({
                layForm: form,
                data: {
                    cityId: '${activity.cityId}',
                    areaInput: '${activity.area}',
                    place: '${activity.place}',
                    cityName: '${cityName}',
                    lat: '${activity.lat}',
                    lng: '${activity.lng}'
                }
            });
            txz.saveStatus = false;
        });
        ue.addListener('ready', function () {
            this.setHeight(500);
            if ($("#contentView").html() != "") {
                this.setHeight(850);
            }
            this.setContent($("#contentView").html());
            //等待ueditor加载完后加载缓存
            if (!'${activity.id}') {
                formcache = new fCache({
                    fCacheKey: 'form_cache_act',//暂存的key
                    cacheCallback: loadCacheData,//获取到缓存后加载的方法
                    getFormData: getFormData
                }).init();
            }
        });

        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });

        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.ACTIVITY.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
    })

    function getFormData() {
        $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
        var formData = util.serializeForm($('#myForm').serializeArray());
        return formData;
    }

    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        //是否收费
        if (cacheData['isFree']) {
            radioValue = cacheData['isFree'];
            if (radioValue == "noFree") {
                $("[name=price]").prop("disabled", false);
            } else {
                $("[name=price]").val("");
                $("[name=price]").prop("disabled", true);
            }
        }
        //加载封面图
        if (cacheData['pic']) {
            $('#cover-img').css('background-image', 'url(' + cacheData['pic'] + ')');
        }
        form.render();
        txz.Map.init({
            layForm: form,
            data: {
                cityId: cacheData.cityId,
                areaInput: cacheData.areaSelect || cacheData.areaInput,
                place: cacheData.place,
                lat: cacheData.lat,
                lng: cacheData.lng
            }
        });
    }

    function openSelMemberDialog(that, title, url, width, height) {
        txz.openDialogIframe({
            width: width,
            height: height,
            title: title,
            url: url,
            cb: function (opt) {
                var content = opt.content;
                if (content.doSubmit()) {
                    var data = content.returnData();
                    $('input[name=member]').val(data.id);
                    $('#member_name').val(data.name);
                    groupExpirationDate = data.expirationTime;
                    top.layer.close(opt.index);

                    if (groupExpirationDate) {
                        var expirationDate = new Date(groupExpirationDate);
                        endLaydate.config.max = {
                            year: expirationDate.getFullYear(),
                            month: expirationDate.getMonth(),
                            date: expirationDate.getDate(),
                            hours: expirationDate.getHours(),
                            minutes: expirationDate.getMinutes(),
                            seconds: expirationDate.getSeconds()
                        };
                    }
                }
            }
        })
    }

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.ACTIVITY.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.ACTIVITY.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }
</script>
</body>
</html>